package com.wpml.product.web;

import com.wpml.product.entity.CategoryModel;
import com.wpml.product.service.CategoryService;
import com.wpml.product.vo.Catalog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: wp
 * @date: 2020/5/29
 **/
@Controller
public class IndexController {

    @Resource
    CategoryService categoryService;

//    @Resource
//    private RedisUtil redisUtil;

    @Resource
    private RedissonClient redisson;

    @RequestMapping(value = {"/", "/index.html"})
    public String indexPage(Model model) {

        /*Object val = redisUtil.get(RedisKey.INDEX_CATEGORY_ONE_KEY);
        if (Objects.nonNull(val)) {
            model.addAttribute("categoryList", JSON.parseArray(val.toString(), CategoryModel.class));
        } else {
            List<CategoryModel> levelOneCategoryList = categoryService.getLevelOneCategoryList();

            redisUtil.set(RedisKey.INDEX_CATEGORY_ONE_KEY, JSON.toJSONString(levelOneCategoryList));

            model.addAttribute("categoryList", levelOneCategoryList);
        }*/

        List<CategoryModel> levelOneCategoryList = categoryService.getLevelOneCategoryList();

        model.addAttribute("categoryList", levelOneCategoryList);

        return "index";
    }

    @ResponseBody
    @GetMapping("index/getCatalogJson")
    public Map<String, List<Catalog2Vo>> getCatalogJson() {

        return categoryService.getCatalogJson();
    }


    @ResponseBody
    @GetMapping("index/testRedisson")
    public String testRedisson() {

        RLock lock = redisson.getLock("testRedisson");
        lock.lock();
        try {
            System.out.println("获取锁，执行业务逻辑。。。" + Thread.currentThread().getId());
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } finally {
            System.out.println("释放锁。。。");
            lock.unlock();
        }

        return "testRedisson";
    }
}
